from .load_config import config
import pika,json


class MqRPCDeadMsgConsumer:

    def __init__(self, dead_queue, durable=False):
        # rabbit mq连接凭证 和 参数
        self.credentials = pika.PlainCredentials(config["rabbitmq_user"], config["rabbitmq_pwd"])
        self.connect_paras = pika.ConnectionParameters(host=config["rabbitmq_host"], port=config.getint("rabbitmq_port")
                                                       , credentials=self.credentials,
                                                       virtual_host=config["rabbitmq_vhost"])

        self.dead_queue = dead_queue
        self.durable = durable

    def status(self):
        # 这里返回连接的状态
        return self.connection.is_open

    def __connect(self):
        # 连接mq
        self.connection = pika.BlockingConnection(self.connect_paras)
        self.channel = self.connection.channel()

        # 声明死信队列
        self.channel.queue_declare(queue=self.dead_queue, durable=self.durable)

        # 设置回调函数
        self.channel.basic_consume(self.on_request, queue=self.dead_queue, no_ack=True)
        # 负载均衡相关
        self.channel.basic_qos(prefetch_count=1)

    def on_request(self, ch, method, props, body):
        response = {"status": "100", "reason": "", "data":None, "exception": ""}
        ch.basic_publish(exchange='',
                         routing_key=props.reply_to,
                         properties=pika.BasicProperties(correlation_id=props.correlation_id),
                         body=json.dumps(response))

    def start_consume(self):
        self.__connect()
        self.channel.start_consuming()